<template>
  <page-header-wrapper>
    <page-tab-list></page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="float: right">
        <a-button type="primary" @click="onEdit" icon="plus">新增</a-button>
        <a-button type="primary" @click="kdniaoApiConfig" icon="plus">电子面单配置</a-button>
      </div>
      <a-divider />
      <a-table
        ref="table"
        size="default"
        row-key="id"
        :columns="columns"
        :data-source="loadData"
        :pagination="false"
      >
        <a-space slot="action" slot-scope="text, item">
          <a-button type="link" @click="onEdit(item.id)">编辑</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="onConfirmStatus('is_delete', item.id)">删除</a-button>
        </a-space>
      </a-table>
    </a-card>
    <a-modal
      title="面单打印编辑"
      @cancel="onClose"
       @ok="onSave"
      okText="保存"
      :destroyOnClose="true"
      :width="800"
      :bodyStyle="{maxHeight:'500px',overflowY:'scroll'}"
      :visible="visible">
      <a-row v-if="loading" style="text-align: center;"><a-spin /></a-row>
      <template v-else>
        <a-form
          action=""
          method="post"
          :form="form">
          <a-form-item :hidden="true" >
            <a-input
              v-decorator="['id']"
              type="number"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="选择快递公司" hasFeedback >
            <a-select
              placeholder="选择快递公司"
              @change="e => expressChange(e)"
              v-decorator="['express_id', { rules: [ { required: true, message: '请选择快递公司' } ] }]">
              <a-select-option
                v-for="(expressItem) of expressList"
                :value="expressItem.id"
                :key="expressItem.id">
                {{ expressItem.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            help="与快递网点申请"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="电子面单客户账号"
            hasFeedback >
            <a-input
              placeholder="电子面单客户账号"
              v-decorator="['customer_name', { rules: [ { required: true, message: '请填写电子面单客户账号' } ] } ]"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="电子面单密码" hasFeedback >
            <a-input
              placeholder="电子面单密码"
              v-decorator="['customer_pwd']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="月结编码" hasFeedback >
            <a-input
              placeholder="月结编码"
              v-decorator="['month_code']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="网点编码" hasFeedback >
            <a-input
              placeholder="网点编码"
              v-decorator="['send_site']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="网点名称" hasFeedback >
            <a-input
              placeholder="网点名称"
              v-decorator="['send_name']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item v-if="selectSize.length > 0" :labelCol="labelCol" :wrapperCol="wrapperCol" label="电子面单模板规格" hasFeedback >
            <a-select
              placeholder="选择电子面单模板规格"
              v-decorator="['template_size']">
              <a-select-option
                v-for="(item) of selectSize"
                :value="item.value"
                :key="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发件人公司" hasFeedback >
            <a-input
              placeholder="发件人公司"
              v-decorator="['company']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发件人名称" hasFeedback >
            <a-input
              placeholder="发件人名称"
              v-decorator="['name']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发件人电话" hasFeedback >
            <a-input
              placeholder="发件人电话"
              v-decorator="['tel']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发件人手机" hasFeedback >
            <a-input
              placeholder="发件人手机"
              v-decorator="['mobile']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发件人邮编" hasFeedback >
            <a-input
              placeholder="发件人邮编"
              v-decorator="['post_code']"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发件人地址" hasFeedback >
            <city-select
              v-model="area"
              :props="{ expandTrigger: 'hover' }"
              data-type="area"
              value-type="2"
            >
            </city-select>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发件人详细地址" hasFeedback style="margin-bottom:150px">
            <a-textarea
              placeholder="请填写详细地址"
              v-decorator="['address']"
              :step="1"
            />
          </a-form-item>
        </a-form>
      </template>
    </a-modal>
    <a-modal destroyOnClose v-model="kdniao_show" title="快递鸟设置" @ok="onKdniaoSave">
      <a-form action="" method="post" :form="kdniaoForm">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="使用快递鸟免费接口">
          <a-radio-group name="kdniao_api_free" v-decorator="['kdniao_api_free']">
            <a-radio :value="1"> 开 </a-radio>
            <a-radio :value="0"> 关 </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="快递鸟商户ID" hasFeedback >
          <a-input
            placeholder="快递鸟商户ID"
            v-decorator="['kdniao_mch_id']"
            type="text"
            :step="1"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="快递鸟API KEY" hasFeedback >
          <a-input
            placeholder="快递鸟API KEY"
            v-decorator="['kdniao_api_key']"
            type="text"
            :step="1"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { List, Edit, Save, Del, SaveKdniaoConfig } from '@/api/setting/express'
import CitySelect from '@/components/CitySelect/CitySelect'
import { STable } from '@/components'
import pick from 'lodash.pick'

const columns = [
  {
    title: '快递公司',
    dataIndex: 'express_name'
  },
  {
    title: '网点名称',
    dataIndex: 'send_name'
  },
  {
    title: '网点编码',
    dataIndex: 'send_site'
  },
  {
    title: '发件人信息',
    dataIndex: 'name'
  },
  {
    title: '操作',
    width:200,
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Express',
  components: {
    STable,
    CitySelect
  },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      kdniaoForm: this.$form.createForm(this),
      kdniaoSetting: {
        kdniao_mch_id: '',
        kdniao_api_key: '',
        kdniao_api_free: 1
      },
      columns: columns,
      expressList: [], // 可选快递
      getTemplateSize: [], // 电子面单模板规格
      selectSize: [], // 可选模板规格
      loading: false,
      visible: false,
      express: {},
      loadData: [],
      area:[],
      kdniao_show: false,
    }
  },
  created () {
    this.getList()
  },
  watch: {
    express (value) {
      this.updateData()
    }
  },
  methods: {
    onKdniaoClose() {
      this.kdniao_show = false;
    },
    onKdniaoSave(e) {
      e.preventDefault()
      this.kdniaoForm.validateFields((err, values) => {
        if (!err) {
          this.$message.loading({ content: '提交中', key: 'updatable' })
          SaveKdniaoConfig(values).then((res) => {
            if (res.code === 0) {
              this.$message.success({ content: res.msg, key: 'updatable' })
              this.$nextTick(() => {
                this.visible = false
                this.getList()
              })
            } else {
              this.$message.error({ content: res.msg, key: 'updatable' })
            }
          })
        } else {
          for (const key in err) {
            this.$message.error(err[key].errors[0].message)
          }
          return false
        }
      })
      this.kdniao_show = false;
    },
    kdniaoApiConfig() {
      this.kdniao_show = true;
      this.updateSetting()
    },
    updateSetting() {
      this.$nextTick(() => {
        this.kdniaoForm.setFieldsValue({
          kdniao_mch_id: this.kdniaoSetting ? this.kdniaoSetting.kdniao_mch_id : '',
          kdniao_api_key: this.kdniaoSetting ? this.kdniaoSetting.kdniao_api_key : '',
          kdniao_api_free: this.kdniaoSetting ? this.kdniaoSetting.kdniao_api_free : 1,
        })
      })
    },
    getList (parameter) {
      this.loadData = null
      return List(parameter)
      .then(res => {
        this.loadData = res.data.list
        this.expressList = res.data.express_list
        this.getTemplateSize = res.data.getTemplateSize
        this.kdniaoSetting = res.data.kdniaoConfig
      })
    },
    onEdit (id) {
      this.visible = true
      this.loading = true
      this.selectSize = []
      Edit({ id: id }).then(res => {
        this.express = res.data.model ? res.data.model : {}
        this.area[0] = this.express.province
        this.area[1] = this.express.city
        this.area[2] = this.express.exp_area
        this.loading = false
      })
    },
    /**
     * 渲染form表单
     */
    updateData () {
      this.$nextTick(() => {
        this.express.express_id = this.express.express_id ? this.express.express_id - 0 : 1
        this.form.setFieldsValue(pick(this.express, ['id', 'express_id', 'customer_name', 'customer_pwd',
        'month_code', 'send_site', 'send_name', 'company', 'name', 'tel', 'mobile', 'post_code', 'address']))
        if (this.express && this.express.express_id) {
          this.expressChange(this.express.express_id, 1)
        }
      })
    },
    expressChange (e, isUp = 0) {
      this.expressList.forEach(element => {
        if (element.id === (e - 0)) {
          if (this.getTemplateSize[element.code]) {
            this.selectSize = this.getTemplateSize[element.code]
            this.$nextTick(() => {
              if (isUp !== 1) {
                this.form.setFieldsValue({ template_size: '' })
              } else {
                this.form.setFieldsValue({ template_size: this.express.template_size })
              }
            })
          } else {
            this.selectSize = []
          }
        }
      })
    },
    onSave (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$message.loading({ content: '提交中', key: 'updatable' })
          values.province = this.area[0]
          values.city = this.area[1]
          values.exp_area = this.area[2]
          Save(values).then(res => {
            if (res.code === 0) {
              this.$message.success({ content: res.msg, key: 'updatable' })
              this.$nextTick(() => {
                this.visible = false
                this.getList()
              })
            } else {
              this.$message.error({ content: res.msg, key: 'updatable' })
            }
          })
        } else {
          console.log(err)
          for (const key in err) {
            this.$message.error(err[key].errors[0].message)
          }
        }
      })
    },
    onClose () {
      this.visible = false
      this.loading = false
      this.express = {}
    },
    showInfo () {
      this.showInfoStatus = true
    },
    handleOk () {
      this.showInfoStatus = false
    },
    onConfirmStatus (type, id) {
      var that = this
      this.$confirm({
        content: '是否确认删除',
        onOk () {
          that.updateStatus({ id: id })
        }
      })
    },
    updateStatus (q) {
      Del(q).then(res => {
        if (res.code === 0) {
          this.getList()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.required::before {
  content: '*';
  color: red;
}
</style>
